#! /usr/bin/python
# coding=utf-8
import time
import os,sys,re
import ConfigParser

config_file="config.ini"
cf = ConfigParser.ConfigParser()
cf.read(config_file)


if os.path.isfile(config_file):
	eth0=cf.get('dev','eth')
	wlan0=cf.get('dev','wlan')
	tun0=cf.get('dev','tun')
else:
	eth0="eth0"#有线设备
	wlan0="wlan0"#无线设备 
	tun0="tun0"#vpn虚拟网络设备

def exchange_mask(mask):
    """
    转换子网掩码格式
    """
    # 计算二进制字符串中 '1' 的个数
    count_bit = lambda bin_str: len([i for i in bin_str if i=='1'])
    # 分割字符串格式的子网掩码为四段列表
    mask_splited = mask.split('.')
    # 转换各段子网掩码为二进制, 计算十进制
    mask_count = [count_bit(bin(int(i))) for i in mask_splited]
    return sum(mask_count)

def get_item(item,interface):
	try:	
		lines=os.popen("ifconfig "+interface).readlines()
		line=lines[1]
	except:
		print interface+" 不存在"
		return False
	ma=re.compile('.*'+item+':([^\s]*)').match(line)
	if ma != None:
		return ma.group(1) 
	else:
		return	False
def get_ip(eth0,wlan0,tun0):
	print ""
#eth0 有线网路设备
eth0_ip=get_item("inet addr",eth0)
if eth0_ip == False:
	print eth0+" error"
	print "请检查网线是否插好，并且"+eth0+"已经正确配置"
else:
	print eth0+" ok "
	print "eth0_ip="+eth0_ip
#wlan 无线网络设备
ip=get_item("inet addr",wlan0)
if ip == False:
	print wlan0+" error"
	print "请检查无线网卡已经插好，hosapd服务已经启动，网卡已经配置好静态ip地址"
	quit()
mask=get_item("Mask",wlan0)
wlan0_ip=ip+"/"+str(exchange_mask(mask))
print wlan0+" ok"
print "wlan0_ip="+wlan0_ip

#tun0 vpn虚拟网络设备
vpn_ip=get_item("inet addr",tun0)
if vpn_ip == False:
	print tun0,"error"
	print "请检查vpn客户端已经连接，并且已经正确获取ip地址"
	quit()
else:
	print tun0,"ok"
	print "tun0_ip="+vpn_ip
ptp=get_item("P-t-P",tun0)
print "p-t-p:"+ ptp

print "检查通过 请运行一下命令生成 路由及转发脚本"
print "./build_sh.py ",vpn_ip,ptp,eth0_ip,wlan0_ip
if cf.has_section("ip")==False:
	cf.add_section("ip")
cf.set('ip',"vpn_ip",vpn_ip)
cf.set('ip',"ptp",ptp)
cf.set('ip',"eth0_ip",eth0_ip)
cf.set('ip',"wlan0_ip",wlan0_ip)
cf.write(open(config_file,"w"))
